# -*- coding: cp1251 -*-
import socket

print 'Started'
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 1024*1024 * 100)
s.bind(('0.0.0.0', 5001))

print 'Binded - wait connection...'
packetID, addr = s.recvfrom(4)
print 'From ', str(addr), ' packet id: ', str(packetID)

s.sendto('sssss', addr)

dg, addr = s.recvfrom(2)
print 'From ', str(addr), ' dg: ', str(dg)

transID, addr = s.recvfrom(8)
print 'From ', str(addr), ' transmitter id: ', str(transID)

reserved, addr = s.recvfrom(8)
print 'From ', str(addr), ' reserved: ', str(reserved)

numReports, addr = s.recvfrom(8)
print 'From ', str(addr), ' report num: ', str(numReports)

'''
    def recv(self):
        global BINSOCKET_BUFFSIZE
        if not self.isClient:
            raise RuntimeError('BinarySocket::recv: socket is not listener and can\'t receive')
        #receive 4byte packet id and ack it by 'sssss'
        packetID = self.sock.recv(4)
        self.sock.send(BINSOCKET_ACK)

        #now receive header with num of reports
        headerSizeExpected = 20
        header = ''
        while len(header) < int(headerSizeExpected):
            buff = self.sock.recv(int(headerSizeExpected))
            header += buff

        if len(header) != headerSizeExpected: raise RuntimeError('BinarySocket::recv: wrong header size %d' % (len(header)))

        dataSizeExpected    = 1024 * 64
        reportNumExpected   = int(header[18:20])
        data = []
        report = ''
        gotNum = 0
        while len(report) < dataSizeExpected and gotNum < reportNumExpected:
            buff = self.sock.recv(int(dataSizeExpected - len(report)))
            report += buff
            if len(report) == dataSizeExpected:
                data.append(report)
                report = ''
                gotNum += 1

        self.sock.send('\r\n\r\n\r\n1111000000000000\r\n')
        return (header, data)

#COMMON METHODS:
    def close(self):
        self.sock.close()


s = BinarySocket()
print 'Started'
s.listen('0.0.0.0', 5001)
print 'Listening...'
#w = s.accept() #indefinite wait
print 'Connected'
s.isClient = True
h, d = s.recv()
print 'Received'
print str(h), str(d)
'''
